package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.minio.MinIOService;
import com.heima.common.util.MediaThreadLocalUtil;
import com.heima.media.dto.WmMaterialDto;
import com.heima.media.entity.WmMaterial;
import com.heima.media.mapper.WmMaterialMapper;
import com.heima.media.service.IWmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-08-09
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements IWmMaterialService {

    @Autowired
    MinIOService minIOService;
    //上传图片
    @Override
    public ResponseResult<WmMaterial> upload(MultipartFile file) {
        //从本地线程获取用户信息
        User user = MediaThreadLocalUtil.get();
        //如果用户为空，提示需要登录
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //调用minio文件获取上传的url地址
        String url = minIOService.upload(file);
        //构建素材表对象
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(user.getUserId());
        wmMaterial.setType(0);
        wmMaterial.setIsCollection(false);
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setUrl(url);
        //保存素材表对象
        this.save(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    //分页查询素材列表
    @Override
    public ResponseResult listByCollection(WmMaterialDto dto) {
        //从本地线程获取用户信息
        User user = MediaThreadLocalUtil.get();
        //如果用户为空，提示需要登录
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //分页查询素材列表
        IPage<WmMaterial> pageParam = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmMaterial> qw = new LambdaQueryWrapper<>();
        if (dto.getIsCollection() != null) {
            qw.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //排序
        qw.orderByDesc(WmMaterial::getCreatedTime);
        //用户只能查看自己上传的图片
        qw.eq(WmMaterial::getUserId,user.getUserId()); //隐藏条件
        IPage<WmMaterial> iPage = this.page(pageParam, qw);
        return new PageResponseResult(dto.getPage(),dto.getSize(),iPage.getTotal(),iPage.getRecords());
    }
}
